import { useRef, useState } from "react";

export default function Coordinate() {

    const [locate, setLocate] = useState({})
    const ref = useRef()
    const windowToCanvas = (canvas, x, y) => {
        const box = canvas.getBoundingClientRect()
        return {
            x: (x - box.left) * (canvas.width / box.width),
            y: (y - box.top) * (canvas.height / box.height)
        }
    }
    const handleMouseMove = (e) => {
        const location = windowToCanvas(ref.current, e.clientX, e.clientY),
            context = ref.current.getContext('2d')
        setLocate(location)
        context.clearRect(0, 0, ref.current.width, ref.current.height)

        context.beginPath()
        context.moveTo(location.x, 0)
        context.lineTo(location.x, ref.current.height)
        context.setLineDash([5, 10])
        context.stroke()
        context.closePath()

        context.beginPath()
        context.moveTo(0, location.y)
        context.lineTo(ref.current.width, location.y)
        context.setLineDash([5, 10])
        context.stroke()
        context.closePath()
    }

    const clearCanvas = () => {
        const context = ref.current.getContext('2d')
        context.clearRect(0, 0, ref.current.width, ref.current.height)
        setLocate({})
    }

    return (
        <div className="flex p-2">
            <canvas width={500} height={500} className="border-2 border-blue-400" ref={ref}
                onMouseMove={event => handleMouseMove(event)} onMouseLeave={() => clearCanvas()}></canvas>
            {locate.x && (<div className="ml-5">
                <div className="text-lg font-mono">x: {locate.x}</div>
                <div className="text-lg font-mono">y: {locate.y}</div>
            </div>)}
        </div>
    )
}